package com.yafengliang.fileupload.controller;

import com.yafengliang.fileupload.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * @author liangyafeng
 * @Description:
 * @date 2020/4/21 17:01
 */
@Controller
@Slf4j
public class UploadController {

    //配置文件中配置要上传文件保存的路径

    @Value("${filePath}")
    private String filePath;

    @RequestMapping(value = "File")
    public String toFile() {
        return "FileUpload";
    }


    @RequestMapping(value = "import", method = RequestMethod.POST)
    public ResponseEntity importFile(@RequestParam("fileUpload") MultipartFile[] fileUpload) {
        String[] str = new String[fileUpload.length];
        //服务器中文件不存在，就创建配置文件中的文件夹
        File[] files = new File(filePath).listFiles();
        if (files == null) {
            new File(filePath).mkdirs();
        }
        try {
            for (int i = 0; i < fileUpload.length; i++) {
                String fileName = fileUpload[i].getOriginalFilename();
                File file = new File(filePath, fileName);
                InputStream is = fileUpload[i].getInputStream();
                FileOutputStream fos = new FileOutputStream(file);
                byte[] bytes = new byte[1024];
                int length;
                while ((length = is.read(bytes)) != -1) {
                    fos.write(bytes, 0, length);
                }
                is.close();
                fos.close();
                str[i] = file.getAbsolutePath();
                log.info("upload {} success",fileName);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(new Result(null, true), HttpStatus.OK);
    }

}
